package com.weme.common.activity

import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import com.weme.common.R
import com.weme.common.base.BaseActivity


class ExoPlayerActivity : BaseActivity() {
    private lateinit var playerView: PlayerView
    private lateinit var player: ExoPlayer
    private var playbackPosition: Long = 0

    @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
    override fun initView(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_exo_player)
        playerView = findViewById(R.id.playerView)
        val  ibBack = findViewById<ImageView>(R.id.ibBack)
        ibBack.setOnClickListener { finish() }
        playerView.transitionName = "thumbnailTransition"
        postponeEnterTransition()
        // 创建 ExoPlayer 实例


        player = ExoPlayer.Builder(this).build()
        playerView.player = player
        playerView.controllerShowTimeoutMs = 0
        playerView.controllerHideOnTouch = false
        player.repeatMode = Player.REPEAT_MODE_ONE

        //填充媒体数据
        player.addMediaItem(MediaItem.fromUri(intent.getStringExtra("url").toString()))
        //准备播放
        player.prepare()


        // 恢复播放位置（如果有保存的位置）
        if (playbackPosition > 0) {
            player.seekTo(playbackPosition)
        }
        player.addListener(object : Player.Listener {
            override fun onEvents(player: Player, events: Player.Events) {
                super.onEvents(player, events)

            }

            override fun onPlayerError(error: PlaybackException) {
                super.onPlayerError(error)
                Log.e("tag", error.errorCode.toString() + "" + error.errorCodeName)
            }

            override fun onPositionDiscontinuity(
                oldPosition: Player.PositionInfo,
                newPosition: Player.PositionInfo,
                reason: Int
            ) {
                super.onPositionDiscontinuity(oldPosition, newPosition, reason)
                println("Position, ${oldPosition}, ${newPosition}")
            }
        })

        // 开始播放
        player.playWhenReady = true
    }

    override fun onStop() {
        super.onStop()
        playerView.onPause() // 暂停播放
    }

    override fun onPause() {
        super.onPause()
        player.playWhenReady = false
        // 保存当前播放位置
        playbackPosition = player.currentPosition
    }

    override fun onResume() {
        super.onResume()
        player.playWhenReady = true
    }


    override fun finish() {
        super.finish()
        player.release()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 释放播放器资源
        player.release()
    }
}

